# coding: utf-8
# 报价工具API

import time

from flask import request
from flask_restful import Api, Resource

from app.api.codes import PARAMS_ILLEGAL, SUCCESS, PRODUCT_ERROR, \
    PRODUCT_NOT_FOUND
from app.api.constant import IsSelf
from app.api.qt_schemas import condition_schema, option_schema, \
    product_detail_schema, product_price_schema
from app.api.supplier_codes import NOT_ENGINEER
from app.api.views import Response, AuthResource
from app.compute.compute_process import ApiProcess
from app.exceptions import NotProductError, InputError
from app.op.constant import UserType
from app.products.models import ProductTemplate, ProductToParam, ProductPrice
from app.token import AuthToken

api = Api()


@api.resource('/compute/prices')
class ComputePrices(Resource):
    """
    create by ld_wu 2017-09-18
    计算价格接口
    """

    def post(self):

        # 前端SEM着陆页需要移除登录限制2018-01-02
        token = request.cookies.get('opc_token')
        user = AuthToken.verify_auth_token(token) if token else None

        data, errors = condition_schema.load(request.form)
        if errors:
            return Response(
                PARAMS_ILLEGAL.new_format_msg(list(errors.values())[0][0])
            )
        try:
            compute_obj = ApiProcess(data, user)
            prices, total = compute_obj.quotation_models()
        except (NotProductError, InputError) as e:
            return Response(PRODUCT_ERROR.new_format_msg(str(e)))

        return Response(
            SUCCESS,
            dict(
                prices=prices,
                screen_high='{0:.2f}'.format(compute_obj.screen_high / 1000),
                screen_wide='{0:.2f}'.format(compute_obj.screen_wide / 1000),
                total='{0:.2f}'.format(total)
            )
        )


@api.resource('/option/products')
class OptionProducts(AuthResource):
    """
    create by ld_wu 2017-09-18
    产品下拉选择框
    """

    def post(self):
        # 不是工程商则直接返回
        if self.user.type != UserType.ENGINEER.value:
            return Response(NOT_ENGINEER)

        data, errors = option_schema.load(request.form)
        if errors:
            return Response(
                PARAMS_ILLEGAL.new_format_msg(list(errors.values())[0][0])
            )
        try:
            compute_obj = ApiProcess(data, self.user)
            options = compute_obj.get_options()
        except (NotProductError, InputError) as e:
            options = list()

        return Response(
            SUCCESS,
            dict(
                options=options,
            )
        )


@api.resource('/product/detail')
class ProductDetail(AuthResource):
    """
    create by ld_wu 2017-09-19
    产品详情
    """

    def post(self):
        # 不是工程商则直接返回
        if self.user.type != UserType.ENGINEER.value:
            return Response(NOT_ENGINEER)

        data, errors = product_detail_schema.load(request.form)
        if errors:
            return Response(
                PARAMS_ILLEGAL.new_format_msg(list(errors.values())[0][0])
            )
        product_id = data['product_id']
        product = ProductTemplate.get_by_id(product_id)
        if not product:
            return Response(PRODUCT_NOT_FOUND)
        product_specs = ProductToParam.get_list_by_args(product_template_id=product_id)

        product_specs = [dict(
            value=item.value,
            name=item.name,
            unit_display=item.unit_display
        ) for item in product_specs]
        return Response(
            SUCCESS,
            dict(
                products=dict(
                    product_id=product.id,
                    product_name=product.name,
                    brand=product.brand,
                    price='{0:.2f}'.format(
                        product.product_price(self.user)
                    ),
                    product_price='{0:.2f}'.format(product.suggest_price),
                    is_self=getattr(product, 'is_self', False),
                    color=product.color_display,
                    scene_type=product.scene_display,
                    transport=product.transport_display,
                    waterproof=product.waterproof_display
                ),
                product_specs=product_specs
            )
        )


@api.resource('/product/price')
class ProductPriceResource(AuthResource):
    """
    create by ld_wu 2017-09-27
    供应商自行供货价格记录
    每个用户每种产品只保存一个价格
    """

    def post(self):
        # 不是工程商则直接返回
        if self.user.type != UserType.ENGINEER.value:
            return Response(NOT_ENGINEER)

        is_self = request.form.get('is_self', 1, type=int)
        if is_self == IsSelf.YES:
            data, errors = product_price_schema.load(request.form)
            if errors:
                return Response(
                    PARAMS_ILLEGAL.new_format_msg(list(errors.values())[0][0])
                )
            product_id = data['product_id']
            price = data['price']

            product = ProductTemplate.get_by_id(product_id)
            if not product:
                return Response(PRODUCT_NOT_FOUND)

            ProductPrice.update_price(product_id, self.user.id, price)
        else:
            data, errors = product_detail_schema.load(request.form)
            if errors:
                return Response(
                    PARAMS_ILLEGAL.new_format_msg(list(errors.values())[0][0])
                )
            product_id = data['product_id']
            product_price = ProductPrice.get_by_args(
                supplier_id=self.user.id,
                product_template_id=product_id
            )
            if product_price:
                product_price.deleted_at = int(time.time())

        return Response(SUCCESS)
